package com.aiapphub.BaseCode.runner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.aiapphub.BaseCode.entity.SsoUser;
import com.aiapphub.BaseCode.service.SsoUserService;
import com.aiapphub.BaseCode.utils.TokenUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class SSOUserFullDataSync {

    private static final Logger logger = LoggerFactory.getLogger(SSOUserDataSync.class);

    @Autowired
    private RestTemplate restTemplate; // 注入 RestTemplate

    @Autowired
    private TokenUtil tokenUtil;

    @Value("${sso.data.url.userData}")
    private String userDataUrl; // 组织数据API URL
    private String accessToken; // 存储访问令牌
    private final ObjectMapper objectMapper = new ObjectMapper(); // 复用 ObjectMapper 实例

    @Autowired
    private SsoUserService ssoUserService;

    // 修改为全量同步，手动调用该方法
    public void userDataSync() {
        try {
            accessToken = tokenUtil.fetchToken(); // 使用 TokenUtil 获取访问令牌
        } catch (IOException e) {
            logger.error("获取TOKEN失败", e);
            return;
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            headers.set("Authorization", "Bearer " + accessToken);

            // 设置固定的起始时间：2019年1月1日 0点0分0秒
            String currentDateTime = "2019-01-01 00:00:00";
            String requestJson = String.format("{\"dateTime\": \"%s\", \"pageNo\": 1, \"pageSize\": 1000, \"extraAttrs\": 1}", currentDateTime);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<String> response = restTemplate.exchange(userDataUrl, HttpMethod.POST, requestEntity, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                handleUserApiResponse(response);
                logger.info("用户API调用成功，时间: {}", currentDateTime);
            } else {
                logger.warn("用户API调用失败，状态码: {}", response.getStatusCode());
            }
        } catch (Exception e) {
            logger.error("调用用户API失败", e);
        }
    }

    private void handleUserApiResponse(ResponseEntity<String> response) {
        if (response.getStatusCode().is2xxSuccessful()) {
            logger.info("用户API响应: {}", response.getBody());
            try {
                processUserApiResponse(response.getBody());
            } catch (IOException e) {
                logger.error("解析用户API响应失败: {}", e.getMessage());
            }
        } else {
            logger.warn("用户API调用失败，状态: {}, 内容: {}", response.getStatusCode(), response.getBody());
        }
    }

    private void processUserApiResponse(String responseBody) throws IOException {
        JsonNode rootNode = objectMapper.readTree(responseBody);
        JsonNode dataNode = rootNode.path("data");

        if (dataNode.isArray()) {
            for (JsonNode node : dataNode) {
                try {
                    // 解析用户信息
                    SsoUser ssoUser = new SsoUser();
                    ssoUser.setOrgNamePath(node.path("orgNamePath").asText());
                    ssoUser.setUserStatus(node.path("userStatus").asInt());
                    ssoUser.setOrgName(node.path("orgName").asText());
                    ssoUser.setSex(node.path("sex").asText());
                    ssoUser.setTelephone(node.path("telephone").asText());
                    ssoUser.setUserName(node.path("userName").asText());
                    ssoUser.setUserSn(node.path("userSn").asText());
                    ssoUser.setEmail(node.path("email").asText());
                    ssoUser.setOrgSn(node.path("orgSn").asText());
                    // 使用 SimpleDateFormat 解析日期
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createTimeStr = node.path("createTime").asText();
                    String updateTimeStr = node.path("updateTime").asText();
                    try {
                        Date createTime = dateFormat.parse(createTimeStr);
                        ssoUser.setCreateTime(createTime);
                    } catch (ParseException e) {
                        logger.error("创建时间解析失败: {}", createTimeStr);
                    }

                    try {
                        Date updateTime = dateFormat.parse(updateTimeStr);
                        ssoUser.setUpdateTime(updateTime);
                    } catch (ParseException e) {
                        logger.error("更新时间解析失败: {}", updateTimeStr);
                    }

                    // 处理账户信息
                    JsonNode acctInfoNode = node.path("acctinfo");
                    if (acctInfoNode.isArray() && acctInfoNode.size() > 0) {
                        JsonNode acctNode = acctInfoNode.get(0); // 假设只取第一个账户信息
                        ssoUser.setAppSn(acctNode.path("APP_SN").asText());
                        ssoUser.setAppName(acctNode.path("APP_NAME").asText());
                        ssoUser.setAcctStatus(acctNode.path("ACCT_STATUS").asInt());
                        ssoUser.setLoginName(acctNode.path("LOGIN_NAME").asText());
                    }
                    // 保存用户信息
                    processUser(ssoUser);
                } catch (Exception e) {
                    logger.error("用户解析失败: {}, 数据: {}", e.getMessage(), node.toString());
                }
            }
            logger.info("用户处理完成，共处理 {} 个用户。", dataNode.size());
        } else {
            logger.warn("用户数据节点不是数组，内容: {}", dataNode.toString());
        }
    }

    private void processUser(SsoUser ssoUser) {
        QueryWrapper<SsoUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_sn", ssoUser.getUserSn());
        if (ssoUserService.count(queryWrapper) > 0) {
            ssoUserService.update(ssoUser, queryWrapper);
            logger.info("更新用户: {}", ssoUser.getUserName());
        } else {
            ssoUserService.save(ssoUser);
            logger.info("成功新增用户: {}", ssoUser.getUserName());
        }
    }
}
